package com.mall.order.services;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.order.OrderQueryService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.converter.OrderConverter;
import com.mall.order.dal.entitys.*;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.OrderShippingMapper;
import com.mall.order.dto.*;
import com.mall.order.utils.ExceptionProcessorUtils;
import com.mall.shopping.constants.ShoppingRetCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 *  ciggar
 * create-date: 2019/7/30-上午10:04
 */
@Slf4j
@Component
@Service
public class OrderQueryServiceImpl implements OrderQueryService {

    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private OrderShippingMapper orderShippingMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderConverter orderConverter;


    @Override
    public OrderListResponse query(OrderListRequest request) {
        OrderListResponse response = new OrderListResponse();
        try {
            Long userId = request.getUserId();
            int page = request.getPage();
            int size = request.getSize();
            PageHelper.startPage(page, size);
            Example example = new Example(Order.class);
            example.setOrderByClause("update_time desc");
            example.createCriteria()
                    .andEqualTo("userId", userId)
                    .andNotEqualTo("status", 8);
            List<Order> orders = orderMapper.selectByExample(example);
            PageInfo<Order> orderPageInfo = new PageInfo<>(orders);
            //List<OrderDetailInfo> orderDetailInfos = orderConverter.orders2details(orders);
            List<OrderDetailInfo> orderDetailInfos = new ArrayList<>();
            for (Order order : orders) {
                OrderDetailInfo orderDetailInfo = orderConverter.order2detail(order);
                String orderId = order.getOrderId();
                Example example1 = new Example(OrderItem.class);
                example1.createCriteria().andEqualTo("orderId", orderId);
                List<OrderItem> orderItems = orderItemMapper.selectByExample(example1);
                for (OrderItem orderItem : orderItems) {
                    String picPath = orderItem.getPicPath();
                    if (picPath != null && !"".equals(picPath)) {
                        String[] strings = picPath.split(",");
                        orderItem.setPicPath(strings[0]);
                    }
                }
                List<OrderItemDto> orderItemDtos = orderConverter.item2dto(orderItems);
                orderDetailInfo.setOrderItemDto(orderItemDtos);

                OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(orderId);
                OrderShippingDto orderShippingDto = orderConverter.shipping2dto(orderShipping);
                orderDetailInfo.setOrderShippingDto(orderShippingDto);

                orderDetailInfos.add(orderDetailInfo);
            }

            response.setDetailInfoList(orderDetailInfos);
            response.setTotal(orderPageInfo.getTotal());
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("OrderQueryServiceImpl.query occur Exception : " + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;
    }

    /**
     * 查询订单详情
     * @param orderDetailRequest
     * @return
     */
    @Override
    @Transactional
    public OrderDetailFinalResponse queryOrderDetail(OrderDetailRequest orderDetailRequest) {

        OrderDetailFinalResponse orderDetailFinalResponse = new OrderDetailFinalResponse();

        try {

            OrderDetailResponse orderDetailResponse = new OrderDetailResponse();

            // 获取订单id
            String orderId = orderDetailRequest.getOrderId();

            // 获取订单信息
            Order order = orderMapper.selectByPrimaryKey(orderId);

            // 获取订单商品
            Example example = new Example(OrderItem.class);
            example.createCriteria().andEqualTo("orderId", orderId);
            List<OrderItem> orderItems = orderItemMapper.selectByExample(example);

            // 获取邮寄信息
            OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(orderId);

            // 封装
            orderDetailResponse = orderConverter.order2res(order);
            List<OrderItemDto> orderItemDtos = orderConverter.item2dto(orderItems);
            OrderShippingDto orderShippingDto = orderConverter.shipping2dto(orderShipping);
            orderDetailResponse.setOrderItemDto(orderItemDtos);
            orderDetailResponse.setOrderShippingDto(orderShippingDto);

            // orderDetailResponse ---> orderDetailFinalDTO
            OrderDetailFinalDTO orderDetailFinalDTO = orderConverter.detailDTO2detailFinalDTO(orderDetailResponse);
            BigDecimal orderTotal = new BigDecimal(0);
            for (OrderItem orderItem : orderItems) {
                orderTotal = orderTotal.add(orderItem.getTotalFee());
            }
            orderDetailFinalDTO.setOrderTotal(orderTotal);
            String streetName = "";
//            streetName = orderShippingDto.getReceiverState()
//                        + orderShippingDto.getReceiverCity()
//                        + orderShippingDto.getReceiverDistrict()
//                        + orderShippingDto.getReceiverAddress();
            streetName = orderShippingDto.getReceiverAddress();
            orderDetailFinalDTO.setStreetName(streetName);
            orderDetailFinalDTO.setUserName(orderShippingDto.getReceiverName());
            orderDetailFinalDTO.setTel(orderShippingDto.getReceiverPhone());

            orderDetailFinalResponse.setOrderDetailFinalDTO(orderDetailFinalDTO);
            orderDetailFinalResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            orderDetailFinalResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        }catch (Exception e) {
            log.error("OrderQueryServiceImpl.queryOrderDetail occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(orderDetailFinalResponse, e);
        }

        return orderDetailFinalResponse;
    }
}
